/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.taglib.core.grid;

import com.blandware.atleap.webapp.taglib.core.BaseHandlerTag;
import com.blandware.atleap.webapp.util.core.RequestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.taglib.TagUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * <p>Tag for marking column as sortable.
 * <br />
 * This tag is only valid when nested within <em>grid</em> tag
 * </p>
 * <p>
 * Allowed attributes are:
 * <ul>
 * <li>
 * <b>fieldName</b> - name of field to sort by
 * </li>
 * <li>
 * <b>property</b> - name of property to lookup value in order to compare
 * entities, when collection is not taken from persistent storage but given to
 * <em>rowsIterator</em> through its <b>collection</b> attribute.
 * </li>
 * <li>
 * <b>rowIterators</b> - comma-separated list of rowIterators IDs this filter
 * is applicable to. This is needed to constrain what row iterators will be
 * affected by this filter (as there may be several row iterators in a single
 * grid) - those IDs must be listed here; if this list is empty or not given,
 * any iterator will match (so this filter will affect all iterators in grid).
 * </li>
 * </ul>
 * </p>
 * <p>
 * This tag must either be contained in <em>column</em> tag or have
 * <b>fieldName</b> specified.
 * </p>
 * <p><a href="SortTag.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.13 $ $Date: 2006/08/03 10:08:21 $
 * @see SortAscTag
 * @see SortDescTag
 * @jsp.tag name="sort"
 * body-content="scriptless"
 * @see com.blandware.atleap.webapp.taglib.core.grid.GridTag
 */
public class SortTag extends BaseHandlerTag {

	protected transient final Log log = LogFactory.getLog(SortTag.class);

	/**
	 * Name of field to sort by
	 */
	protected String fieldName;

	/**
	 * Name of property to lookup value in order to compare entities, when
     * collection is not taken from persistent storage
	 */
	protected String property;

	/**
	 * Comma-separated list of rowIterators IDs this filter is applicable to
	 */
	protected String rowIterators = null;


	/**
     * Returns name of field by which to sort
     *
	 * @return field name
	 * @jsp.attribute required="false"
	 * rtexprvalue="true"
	 * type="java.lang.String"
	 * description="Name of field to sort by"
	 */
	public String getFieldName() {
		return fieldName;
	}

    /**
     * Sets name of field by which to sort
     *
     * @param fieldName field name to set
     */
	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}

	/**
     * Returns name of property by which to compare beans
     *
	 * @return property name
	 * @jsp.attribute required="false"
	 * rtexprvalue="true"
	 * type="java.lang.String"
	 * description="Name of property to lookup value in order to compare entities, when collection is not taken from persistent storage"
	 */
	public String getProperty() {
		return property;
	}

    /**
     * Sets name of property by which to compare beans
     *
     * @param property property name
     */
	public void setProperty(String property) {
		this.property = property;
	}

	/**
     * Returns comma-separated list of rowIterators IDs this filter is
     * applicable to
     *
	 * @return row iterators list
	 * @jsp.attribute required="false"
	 * rtexprvalue="true"
	 * type="java.lang.String"
	 * description="Comma-separated list of rowIterators IDs this filter is applicable to"
	 */
	public String getRowIterators() {
		return rowIterators;
	}

    /**
     * Sets comma-separated list of rowIterators IDs this filter is
     * applicable to
     *
     * @param rowIterators row iterators list to set
     */
	public void setRowIterators(String rowIterators) {
		this.rowIterators = rowIterators;
	}

    /**
     * Processes the tag
     *
     * @throws JspException
     * @throws IOException
     */
	public void doTag() throws JspException, IOException {

		PageContext pageContext = (PageContext) getJspContext();

		GridTag parentGridTag = (GridTag) findAncestorWithClass(this, GridTag.class);

		if ( parentGridTag == null ) {
			JspTagException e = new JspTagException("Parent tag is invalid! This tag is only valid when nested within 'grid' tag");
			throw e;
		}

		// Get field name from parent 'column' tag
		ColumnTag parentColumnTag = (ColumnTag) findAncestorWithClass(this, ColumnTag.class);
		if ( parentColumnTag != null ) {
			if ( fieldName == null || fieldName.length() == 0 ) {
				fieldName = parentColumnTag.getFieldName();
			}
		}

		if ( fieldName == null || "".equals(fieldName) ) {
			// Error: there is no ancestor 'column' tag and no fieldName attribute is specified
			String errorMessage = "There is no ancestor 'column' tag and no fieldName attribute is specified!";
			if ( log.isErrorEnabled() ) {
				log.error(errorMessage);
			}
			JspTagException e = new JspTagException(errorMessage);
			throw e;
		}

		String pageUrl = parentGridTag.getPageUrl();
		Map parameterMap = parentGridTag.getParameterMap();
		parameterMap.put("sortField", fieldName);
		if ( property != null ) {
			parameterMap.put("property", property);
		}
		parameterMap.put("gridName", parentGridTag.getName());
		parameterMap.put("pageNumber", parentGridTag.getCurrentPageNumber());
		if ( rowIterators != null ) {
			parameterMap.put("rowIterators", rowIterators);
		}

		pageUrl += "?" + RequestUtil.createQueryStringFromMap(parameterMap, "&");

		StringWriter sw = new StringWriter();
		StringBuffer sb = sw.getBuffer();
		sb.append("<a href=\"").append(pageUrl).append("\"").append(prepareAttributes()).append(">");
		getJspBody().invoke(sw);
		sb.append("</a>");
		TagUtils.getInstance().write(pageContext, sw.toString());
	}

}
